package com.zfdang.touchhelper.service;

import android.accessibilityservice.AccessibilityService;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.view.accessibility.AccessibilityEvent;

import androidx.core.app.NotificationCompat;

import com.aivin.adovertool.R;
import com.zfdang.touchhelper.tool.LyAccessibilityServiceTool;

import java.lang.ref.WeakReference;

/**
 * @author ly-dengpw
 */
public class TouchHelperService extends AccessibilityService {
    /**
     * 方便在其他类中调用 service的方法
     */
    private static WeakReference<TouchHelperService> sServiceRef;
    private LyAccessibilityServiceTool serviceTool;

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        sServiceRef = new WeakReference<>(this);
        if (serviceTool == null) {
            serviceTool = new LyAccessibilityServiceTool(this);
        }
        serviceTool.onServiceConnected();
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        if (serviceTool != null) {
            serviceTool.onAccessibilityEvent(event);
        }
    }

    @Override
    public void onInterrupt() {
        if (serviceTool != null) {
            serviceTool.onInterrupt();
        }
    }

    @Override
    public boolean onUnbind(Intent intent) {
        if (serviceTool != null) {
            serviceTool.onUnbind(intent);
            serviceTool = null;
        }
        sServiceRef = null;
        return super.onUnbind(intent);
    }

    public static boolean dispatchAction(int action) {
        final TouchHelperService service = sServiceRef != null ? sServiceRef.get() : null;
        if (service == null || service.serviceTool == null) {
            return false;
        }
        service.serviceTool.receiverHandler.sendEmptyMessage(action);
        return true;
    }

    public static boolean isServiceRunning() {
        final TouchHelperService service = sServiceRef != null ? sServiceRef.get() : null;
        return service != null && service.serviceTool != null;
    }
}
